<template>
    <div class="courseChapterListView">
        <div class="editoButtons" v-if="permission > 1">
            <div class="button" @click="() => {router.push('/course/courseContent/' + courseId)}">章节管理</div>
        </div>
        <div class="empty" v-if="menuLists?.length <= 0">暂无章节列表</div>
        <MenuList :menuList="menuLists" :fontSize="16" @itemClick="handleChapterClick">
            <template #hoverButtons>
                <div class="menuListsButton" v-if="permission > 1">
                  <span> 查看详细 </span>
                </div>
                <div class="menuListsButton" v-else-if="permission > 0">
                  <span> 进入学习 </span>
                </div>
                <div class="menuListsButton" v-else>
                  <span> 需加入课程后学习，点击加入 </span>
                </div>
            </template>
        </MenuList>
    </div>
</template>

<script lang="ts">
import { courseApi } from '@/api/course/Course';
import MenuList from '@/components/MenuList.vue';
import { MenuListItem } from '@/types/MenuListItem';
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';

export default {
    name: 'courseChapterListView',
    components: {
        MenuList
    }
}
</script>

<script setup lang="ts">
    const router = useRouter();     // 获取路由实例
    const route = useRoute();  // 获取路由参数
    const courseId = ref<number | null>(null); // 初始化为 null
    
    const menuLists = ref<MenuListItem[]>([]);

    const props = defineProps<{
        pPermission: number,
        joinCourse: () => Promise<boolean>;
    }>();

    // 获取课程权限
    const permission = ref(0);

    // 获取课程章节及对应课时列表
    const fetchChapterListWithLessons = async (): Promise<MenuListItem[]> => {
        try {
            // 获取章节列表
            const chaptersResponse = await courseApi.chapter.getList(courseId.value);

            // 为每个章节并行获取课时列表
            const chapterPromises = chaptersResponse.data.map(async (chapter) => {
                try {
                    const lessonsResponse = await courseApi.chapter.lessons.getList(chapter.chapterId);

                    return {
                        menuId: `${chapter.chapterId}`,
                        chapterId: chapter.chapterId,
                        name: `第${chapter.displayOrder}章 ${chapter.chapterName}`,
                        icon: '&#xe65c;',
                        children: lessonsResponse.data.map(lesson => ({
                            menuId: `${chapter.chapterId}.${lesson.lessonsId}`,
                            chapterId: chapter.chapterId,
                            lessonId: lesson.lessonsId,
                            name: `${chapter.displayOrder}.${lesson.displayOrder} ${lesson.lessonName}`,
                            icon: '&#xe645;'
                        }))
                    } as MenuListItem;
                } catch (error) {
                    console.error(`获取章节 ${chapter.chapterId} 的课时列表失败:`, error);
                    return {
                        menuId: `${chapter.chapterId}`,
                        chapterId: chapter.chapterId,
                        name: `第${chapter.displayOrder}章 ${chapter.chapterName}`,
                        icon: '&#xe65c;',
                        contract: true,
                        children: []
                    } as MenuListItem;
                }
            });

            // 等待所有章节数据完成
            return await Promise.all(chapterPromises);

        } catch (error) {
            console.error('获取课程章节列表失败:', error);
            return [];
        }
    };

    const handleChapterClick = async (menu: any) => {
        if (permission.value > 0)
        {
            // 处理章节点击事件
            router.push({
                path: `/course/courseContent/${courseId.value}/courseContentChapter`,
                query: { chapterId: menu.chapterId, lessonId: menu.lessonId }
            });
        }
        else {
            const success = await props.joinCourse();
            if(success) router.push({
                path: `/course/courseContent/${courseId.value}/courseContentChapter`,
                query: { chapterId: menu.chapterId, lessonId: menu.lessonId }
            });
        }
    };
    
    // 参数转换函数（确保字符串转换为数字）
    const parseSafeInt = (value: string | string[] | undefined): number | undefined => {
        if (typeof value === 'string') {
            const num = parseInt(value, 10);
            return isNaN(num) ? undefined : num;
        }
        return undefined;
    };
    // 监听路由参数的变化
    watch(() => ({
        chourseIdParam: route.params.courseId,
        permissionParam: props.pPermission
    }), async ({chourseIdParam, permissionParam}) => {
        if(chourseIdParam)
        {
            courseId.value = parseSafeInt(chourseIdParam);
            if(courseId.value) menuLists.value = await fetchChapterListWithLessons();
        }
        if(permissionParam) permission.value = permissionParam;
    }, { immediate: true, deep: true } );
</script>


<style scoped>
.courseChapterListView{
    width: 100%;
    box-sizing: border-box;
    position: relative;
    padding: 20px;
}

.courseChapterListView .menuListsButton {
    display: inline-block;
    font-size: 14px;
    color: rgba(65, 185, 255, 1);
}
.courseChapterListView .empty {
    font-size: 32px;
    font-weight: bold;
	font-family: "artisticFonts";
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(180, 180, 180, 1);
}
/* 编辑按钮 */
.courseChapterListView .editoButtons {
    width: 100%;
    position: relative;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-bottom: 10px;
}
.courseChapterListView .editoButtons .button{
    padding: 5px 10px;
    background-color: rgba(65, 185, 255, 1);
    color: rgba(255, 255, 255, 1);
    border-radius: 5px;
    font-size: 18px;
    margin-right: 10px;
    transition: all 0.3s;
}
.courseChapterListView .editoButtons .button:hover {
    background-color: rgba(65, 185, 255, 0.8);
}
.courseChapterListView .editoButtons .button:active {
    background-color: rgba(65, 185, 255, 0.9);
    transition: all 0.1s;
}
</style>